#!/bin/bash
#
# remote control for X
# this script will send all keypresses

#dep check
XTE=`which xte`;
if [ -e $XTE ];
then
	echo using $XTE;
else
	echo you need xte binary. it came in package xautomation
	die 1;
fi

#some keys constants
ESC=
BACKSPACE=
CTRL_X=
CTRL_C=
UP=OA
DOWN=OB
LEFT=OD
RIGHT=OC
RETURN=


#start vnc
#deinterlace modes does options does not work. nothing. nada. and their bug reporting process is a pain... but it's not needed everytime, so, enable yourself on the menu
VLC=`which vlc`;
$VLC --sout-deinterlace-mode blend --sout-transcode-deinterlace --deinterlace-mode blend \
 --key-chapter-prev r --key-chapter-next t \
 --fullscreen \
 dvd:///dev/scd0@$1  :sub-track=0 > /dev/null &

stty -echo  raw opost
EXIT=0
ESCAPE_ON=0
while EXIT=0; do
	#read -n 1 -s INPUT
	INPUT=$(head -c1);
	echo ${INPUT}
	case "$INPUT" in
		[qQ${CTRL_C}] )
			EXIT=1
			break #bash case does not need break, only ;; this break quits the while
			;;
		"${RETURN}" ) # empty means return
			$XTE "key Return"
			echo Return;
			;;
		[\ ] )
		 # not working :( read -n1 with space return emtpy instead
			echo Space;
			;;
		[[:alnum:]] )
			# key up is 2chars. ESCOA
			if [ $ESCAPE_ON -eq 1 ]; then
				if [ "$INPUT" == "O" ]; then
					echo O; #do nothing, but also does not forget ESCAPE_ON state. we need to read the NEXT char.
				elif [ "$INPUT" == "A" ]; then
					$XTE "key Up";
					echo "Up";
					ESCAPE_ON=0;
				elif [ "$INPUT" == "B" ]; then
					$XTE "key Down";
					echo "Down";
					ESCAPE_ON=0;
				elif [ "$INPUT" == "C" ]; then
					$XTE "key Right";
					echo "Right";
					ESCAPE_ON=0;
				elif [ "$INPUT" == "D" ]; then
					$XTE "key Left";
					echo "Left";
					ESCAPE_ON=0;
				else
					# this is some escaped char that is not the arrowkeys.
					echo "=>" ${INPUT};
					ESCAPE_ON=0
				fi
			else
				$XTE "key $INPUT";
				echo $INPUT;
			fi
			;;
		"${BACKSPACE}" )
			$XTE "mouseclick 3";
			echo backspace;
			;;
		"${ESC}" )
			#we can't use the esc key. because it is used to the arrow chars. also, i don't have escape on my cell keyboard :)
			#pressing the directional keys gives an ESC and O[abcd] for up, down, left, right
			#xte "key Escape";
			ESCAPE_ON=1
			echo ESC
			;;
	esac

done

# exit vlc
$XTE "keydown Control_L" "key x" "keyup Control_L";
$XTE "keydown Control_L" "key q" "keyup Control_L";

#clean up
stty echo cooked
exit 0
